
package coffee;

/**
 *
 * @author bwolff
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Arrays;

public class CoffeeConnector {
    
    	Socket socket;
	PrintWriter outStream;
        ReadInStream readStream;
        
        public CoffeeConnector() {
            try{                
                socket = new Socket(Constants.HOST, Constants.PORT);
                readStream= new ReadInStream(socket);
                readStream.setDaemon(true);
                readStream.start();
                outStream = new PrintWriter(socket.getOutputStream(), true);
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("Could not connect to Server!");
                System.exit(1);
            }
        }
        
        public void sendCommand(int[] commands) {
                // Lesbare Form des gesendeten Befehls ausgeben
                StringBuilder readableCommands = new StringBuilder("Sent: ");
                for(int i : commands) {
                    String s = Constants.map.get(i);
                    if(s != null) {
                        readableCommands.append(s);
                    } else {
                        readableCommands.append(i);
                    }
                    readableCommands.append(" ");
                }
                System.out.println(readableCommands.toString());
                
		String command = Arrays.toString(commands);
		command = command.replaceAll("[,\\[,\\]]", "");
		// hier haben wir den String mit den Zahlen, jeweils durch ein
		// Leerzeichen getrennt.
		if (command != null && command != "" && command.length() > 0) {
			// ueber den PrintWriter an den Server schicken
			outStream.println(command);
			// und zum debuggen mal auf der Konsole ausgeben
			//System.out.println("sent: " + command);
		}

	}
            
}
